'use client'

import { useEffect, useState, useMemo } from 'react'
import { useParams } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import { VmsScript ,AiScript} from '@/types/Model'
import {
  DragDropContext,
  Droppable,
  Draggable,
  DropResult
} from '@hello-pangea/dnd'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { FileText, Plus, Search, Filter } from 'lucide-react'

// 空状态组件
const EmptyState = ({ onCreateScript, isFiltered }: { onCreateScript: () => void, isFiltered: boolean }) => (
  <div className="flex flex-col items-center justify-center py-16 px-4 text-center">
    <div className="w-24 h-24 mx-auto mb-6 text-gray-300">
      <FileText className="w-full h-full" />
    </div>
    <h3 className="text-xl font-semibold text-gray-900 mb-2">
      {isFiltered ? '没有找到匹配的脚本' : '还没有脚本'}
    </h3>
    <p className="text-gray-500 mb-6 max-w-md">
      {isFiltered 
        ? '尝试调整搜索条件或筛选器来查找脚本' 
        : '开始创建您的第一个脚本，或使用AI生成功能快速创建脚本内容'
      }
    </p>
    {!isFiltered && (
      <div className="flex gap-3">
        <Button onClick={onCreateScript} className="flex items-center gap-2">
          <Plus className="w-4 h-4" />
          创建脚本
        </Button>
      </div>
    )}
  </div>
)

export default function ScriptsPage() {
  const searchParams = useParams()
  const copy_id = searchParams.copy_id
  const [scripts, setScripts] = useState<VmsScript[]>([])
  const [loading, setLoading] = useState(true)
  const [editingScript, setEditingScript] = useState<VmsScript | null>(null)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [isCreating, setIsCreating] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedLocation, setSelectedLocation] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [isGenerating, setIsGenerating] = useState(false)
  const [generatedScripts, setGeneratedScripts] = useState<AiScript[]>([])
  const [showGeneratedDialog, setShowGeneratedDialog] = useState(false)


  // Get unique locations from scripts
  const locations = useMemo(() => {
    if (!Array.isArray(scripts)) return []  // 添加数组检查
    const locs = new Set(scripts.map(script => script.location).filter(Boolean))
    return Array.from(locs)
  }, [scripts])

  const filteredScripts = useMemo(() => {
    if (!Array.isArray(scripts)) return []  // 添加数组检查
    let filtered = scripts
    
    // Filter by search query
    if (searchQuery) {
      filtered = filtered.filter(script => 
        script.caption?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        script.plot?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        script.location?.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }

    // Filter by location
    if (selectedLocation !== 'all') {
      filtered = filtered.filter(script => script.location === selectedLocation)
    }

    // Filter by status
    if (selectedStatus !== 'all') {
      const statusFilter = selectedStatus === 'completed'
      filtered = filtered.filter(script => script.finished === statusFilter)
    }

    return filtered
  }, [scripts, searchQuery, selectedLocation, selectedStatus])

  const fetchScripts = async () => {
    try {
      if (!copy_id) return
      
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script?copy_id=${copy_id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to fetch scripts')
      }
      
      const data = await response.json()
      setScripts(Array.isArray(data) ? data : [])  // Ensure data is an array
      
      toast({
        title: '数据获取成功',
        description: '脚本列表已加载',
      })
    } catch (error) {
      console.error('Error fetching scripts:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      setScripts([])  // 出错时设置为空数组
    } finally {
      setLoading(false)
    }
  }

  const handleCreateScript = () => {
    setEditingScript({
      id: "",
      copy_id: typeof copy_id === 'string' ? copy_id : '',
      caption: '',
      content: '',
      scene: 0,
      shot: 0,
      shot_angle: '视平',
      shot_move: '固定',
      shot_size: '中景',
      finished: false,
      pxh: scripts.length + 1,
      psh: scripts.length + 1,
      location: '',
      plot: '',
      cch: ''
    })
    setIsCreating(true)
    setIsDialogOpen(true)
  }

  const handleSaveScript = async () => {
    try {
      const token = localStorage.getItem('token')
      const method = isCreating ? 'POST' : 'PUT'
      const response = await fetch('/api/script', {
        method,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(editingScript)
      })

      if (!response.ok) {
        throw new Error(isCreating ? 'Failed to create script' : 'Failed to save script')
      }

      toast({
        title: isCreating ? '创建成功' : '保存成功',
        description: isCreating ? '新脚本已创建' : '脚本已更新',
      })
      setIsDialogOpen(false)
      setIsCreating(false)
      fetchScripts()
    } catch (error) {
      console.error('Error saving script:', error)
      toast({
        title: isCreating ? '创建失败' : '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const handleDragEnd = async (result: DropResult) => {
    if (!result.destination || result.destination.index === result.source.index) return

    // 先更新本地列表
    const items = Array.from(scripts)
    const [reorderedItem] = items.splice(result.source.index, 1)
    items.splice(result.destination.index, 0, reorderedItem)

    const updatedItems = items.map((item, index) => ({
      ...item,
      pxh: index + 1,
      psh: index + 1
    }))

    // 直接更新UI
    setScripts(updatedItems)

    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/script/batch', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedItems)
      })

      if (!response.ok) {
        throw new Error('Failed to update script order')
      }

      toast({
        title: '排序更新成功',
        description: '脚本顺序已更新',
      })

    } catch (error) {
      console.error('Error updating script order:', error)
      toast({
        title: '排序更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // 失败时恢复原顺序
      setScripts(scripts)
    }
  }

  const handleEditScript = (script: VmsScript) => {
    setEditingScript(script)
    setIsCreating(false)
    setIsDialogOpen(true)
  }

  const handleCompleteScript = async (script: VmsScript) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ...script,
          finished: true
        })
      })

      if (!response.ok) {
        throw new Error('Failed to complete script')
      }

      toast({
        title: '完成状态更新成功',
        description: '脚本已完成',
      })
      fetchScripts()
    } catch (error) {
      console.error('Error completing script:', error)
      toast({
        title: '完成状态更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  useEffect(() => {
    if (copy_id) {
      fetchScripts()
    }
  }, [copy_id])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }


  const handleGenerateScripts = async () => {
    try {
      setIsGenerating(true)
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script/generate?copy_id=${copy_id}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        throw new Error('Failed to generate scripts')
      }

      const data = await response.json()
      // Ensure data is an array
      console.log(data)
      setGeneratedScripts(Array.isArray(data.scripts) ? data.scripts : [])
      setShowGeneratedDialog(true)
      
      toast({
        title: '脚本生成成功',
        description: '请查看并确认生成的脚本',
      })
    } catch (error) {
      console.error('Error generating scripts:', error)
      toast({
        title: '脚本生成失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // Set empty array on error
    setGeneratedScripts([])
    } finally {
      setIsGenerating(false)
    }
  }



  const handleBatchCreate = async () => {

    // 为每个生成的脚本添加copy_id
    const scriptsWithCopyId = generatedScripts.map(script => ({
      ...script,
      copy_id: copy_id
    }))
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/script/batch', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(scriptsWithCopyId)
      })

      if (!response.ok) {
        throw new Error('Failed to create scripts')
      }

      toast({
        title: '批量创建成功',
        description: '脚本已成功添加',
      })
      setShowGeneratedDialog(false)
      fetchScripts()
    } catch (error) {
      console.error('Error creating scripts:', error)
      toast({
        title: '批量创建失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const handleDeleteScript = async (script: VmsScript) => {
    try {
      // 二次确认
      const confirmDelete = window.confirm(`确定要删除脚本 "${script.caption}" 吗？此操作无法撤销。`)
      if (!confirmDelete) return

      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script/${script.id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        throw new Error('Failed to delete script')
      }

      toast({
        title: '删除成功',
        description: '脚本已删除',
      })
      fetchScripts()
    } catch (error) {
      console.error('Error deleting script:', error)
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-6">
        {/* 页面头部 */}
        <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
          <div className="flex flex-col gap-6">
            <div className="flex justify-between items-start">
              <div>
                <h1 className="text-3xl font-bold text-gray-900 mb-2">Scripts</h1>
                <p className="text-gray-600">管理和运行您的脚本</p>
              </div>
              <div className="flex gap-3">
                <Button 
                  variant="outline" 
                  onClick={() => window.location.href = `/copy/${copy_id}`}
                  className="flex items-center gap-2"
                >
                  ← 返回文案
                </Button>
                <Button 
                  variant="destructive" 
                  onClick={handleGenerateScripts}
                  disabled={isGenerating}
                  className="flex items-center gap-2"
                >
                  {isGenerating ? (
                    <>
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      生成中...
                    </>
                  ) : (
                    <>
                      <Plus className="w-4 h-4" />
                      AI生成脚本
                    </>
                  )}
                </Button>
                <Button onClick={handleCreateScript} className="flex items-center gap-2">
                  <Plus className="w-4 h-4" />
                  新增脚本
                </Button>
              </div>
            </div>
            
            {/* 搜索和筛选区域 */}
            <div className="flex flex-wrap gap-4">
              <div className="relative flex-1 min-w-[300px]">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="搜索脚本内容、对白或地点..."
                  className="pl-10"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
              <Select value={selectedLocation} onValueChange={setSelectedLocation}>
                <SelectTrigger className="w-[180px]">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue placeholder="选择场景" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有场景</SelectItem>
                  {locations.map((location) => (
                    <SelectItem key={location} value={location ?? ''}>
                      {location ?? ''}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="选择状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有状态</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="uncompleted">未完成</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {/* 脚本列表区域 */}
        <div className="bg-white rounded-lg shadow-sm border">
          {loading ? (
            <div className="flex items-center justify-center py-16">
              <div className="flex items-center gap-3 text-gray-500">
                <div className="w-6 h-6 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin" />
                加载中...
              </div>
            </div>
          ) : filteredScripts.length === 0 ? (
            <EmptyState 
              onCreateScript={handleCreateScript} 
              isFiltered={searchQuery !== '' || selectedLocation !== 'all' || selectedStatus !== 'all'}
            />
          ) : (
            <div className="p-6">
              {/* 统计信息 */}
              <div className="flex items-center justify-between mb-6 pb-4 border-b">
                <div className="flex items-center gap-6 text-sm text-gray-600">
                  <span>共 {filteredScripts.length} 个脚本</span>
                  <span>已完成 {filteredScripts.filter(s => s.finished).length} 个</span>
                  <span>未完成 {filteredScripts.filter(s => !s.finished).length} 个</span>
                </div>
              </div>

              <DragDropContext onDragEnd={handleDragEnd}>
                <Droppable droppableId="scripts">
                  {(provided) => (
                    <div 
                      {...provided.droppableProps}
                      ref={provided.innerRef}
                      className="space-y-4"
                    >
                      {filteredScripts.map((script, index) => (
                        <Draggable key={script.id} draggableId={script.id} index={index}>
                          {(provided, snapshot) => (
                            <div
                              ref={provided.innerRef}
                              {...provided.draggableProps}
                              {...provided.dragHandleProps}
                              className={`
                                group relative p-6 border rounded-lg transition-all duration-200
                                ${snapshot.isDragging 
                                  ? 'shadow-lg border-blue-300 bg-blue-50' 
                                  : 'hover:shadow-md hover:border-gray-300 bg-white'
                                }
                                ${script.finished ? 'bg-gray-50' : ''}
                              `}
                            >
                              {/* 拖拽指示器 */}
                              <div className="absolute left-2 top-1/2 transform -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity">
                                <div className="w-1 h-8 bg-gray-300 rounded-full" />
                              </div>

                              <div className="ml-4">
                                <div className="grid grid-cols-12 gap-4 items-start">
                                  {/* 镜号 */}
                                  <div className="col-span-1">
                                    {script.pxh && (
                                      <div className="text-xs font-medium text-gray-500 bg-gray-100 px-2 py-1 rounded">
                                        镜号: {script.pxh}
                                      </div>
                                    )}
                                  </div>
                                  
                                  {/* 地点 */}
                                  <div className="col-span-1">
                                    {script.location && (
                                      <div className="text-xs text-gray-600 bg-blue-50 px-2 py-1 rounded">
                                        📍 {script.location}
                                      </div>
                                    )}
                                  </div>
                                  
                                  {/* 情节 */}
                                  <div className="col-span-2">
                                    <h3 className={`text-sm font-semibold ${
                                      script.finished ? 'text-gray-400 line-through' : 'text-gray-900'
                                    }`}>
                                      {script.plot}
                                    </h3>
                                  </div>
                                  
                                  {/* 内容和对白 */}
                                  <div className="col-span-4">
                                    <div className="space-y-2">
                                      <div className={`text-sm ${
                                        script.finished ? 'text-gray-400' : 'text-gray-700'
                                      }`}>
                                        <span className="font-medium">内容：</span>
                                        <span className="line-clamp-2">{script.content}</span>
                                      </div>
                                      <div className={`text-sm ${
                                        script.finished ? 'text-gray-400' : 'text-gray-700'
                                      }`}>
                                        <span className="font-medium">对白：</span>
                                        <span className="line-clamp-2">{script.caption}</span>
                                      </div>
                                    </div>
                                  </div>
                                  
                                  {/* 拍摄参数 */}
                                  <div className="col-span-2">
                                    <div className="flex flex-wrap gap-1">
                                      {script.shot_angle && (
                                        <span className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded">
                                          {script.shot_angle}
                                        </span>
                                      )}
                                      {script.shot_move && (
                                        <span className="text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded">
                                          {script.shot_move}
                                        </span>
                                      )}
                                      {script.shot_size && (
                                        <span className="text-xs bg-orange-100 text-orange-700 px-2 py-1 rounded">
                                          {script.shot_size}
                                        </span>
                                      )}
                                    </div>
                                  </div>
                                  
                                  {/* 状态和操作 */}
                                  <div className="col-span-2">
                                    <div className="flex items-center justify-between">
                                      <span className={`text-xs font-medium px-2 py-1 rounded-full ${
                                        script.finished 
                                          ? 'bg-green-100 text-green-700' 
                                          : 'bg-orange-100 text-orange-700'
                                      }`}>
                                        {script.finished ? '✓ 已完成' : '⏳ 未完成'}
                                      </span>
                                      
                                      <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <Button
                                          variant="ghost"
                                          size="sm"
                                          onClick={() => handleEditScript(script)}
                                          className="h-8 w-8 p-0"
                                        >
                                          ✏️
                                        </Button>
                                        <Button
                                          variant={script.finished ? "default" : "ghost"}
                                          size="sm"
                                          onClick={() => handleCompleteScript(script)}
                                          className="h-8 w-8 p-0"
                                        >
                                          {script.finished ? '↩️' : '✓'}
                                        </Button>
                                        <Button
                                          variant="ghost"
                                          size="sm"
                                          onClick={() => handleDeleteScript(script)}
                                          className="h-8 w-8 p-0 text-red-500 hover:text-red-700"
                                        >
                                          🗑️
                                        </Button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          )}
                        </Draggable>
                      ))}
                      {provided.placeholder}
                    </div>
                  )}
                </Droppable>
              </DragDropContext>
            </div>
          )}
        </div>

        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{isCreating ? '新增脚本' : '编辑脚本'}</DialogTitle>
            </DialogHeader>
            {editingScript && (
              <div className="space-y-4">
                <Input
                  value={editingScript.plot}
                  onChange={(e) => setEditingScript({
                    ...editingScript,
                    plot: e.target.value
                  })}
                  placeholder="情节：主体+动作"
                />

                <Input
                    value={editingScript.location || ''}
                    onChange={(e) => setEditingScript({
                      ...editingScript,
                      location: e.target.value
                    })}
                    placeholder="拍摄地点"
                  />
                
                <Textarea
                  value={editingScript.content}
                  onChange={(e) => setEditingScript({
                    ...editingScript,
                    content: e.target.value
                  })}
                  placeholder="脚本内容"
                  rows={6}
                />
                <Textarea
                  value={editingScript.caption}
                  onChange={(e) => setEditingScript({
                    ...editingScript,
                    caption: e.target.value
                  })}
                  placeholder="对白"
                  rows={6}
                />

                <div className="grid grid-cols-2 gap-4">

                <Select
                    value={editingScript.shot_size || ''}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      shot_size: value
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择景别" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="中景">中景</SelectItem>
                      <SelectItem value="近景">近景</SelectItem>
                      <SelectItem value="远景">远景</SelectItem>
                      <SelectItem value="特写">特写</SelectItem>
                    </SelectContent>
                  </Select>

                  <Select
                    value={editingScript.shot_angle || ''}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      shot_angle: value
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择镜头角度" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="视平">视平</SelectItem>
                      <SelectItem value="仰拍">仰拍</SelectItem>
                      <SelectItem value="俯拍">俯拍</SelectItem>
                      <SelectItem value="斜拍">斜拍</SelectItem>
                      <SelectItem value="越肩">越肩</SelectItem>
                    </SelectContent>
                  </Select>

                  <Select
                    value={editingScript.shot_move || ''}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      shot_move: value
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择运镜方式" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="固定">固定</SelectItem>
                      <SelectItem value="横摇">横摇</SelectItem>
                      <SelectItem value="俯仰">俯仰</SelectItem>
                      <SelectItem value="横移">横移</SelectItem>
                      <SelectItem value="升降">升降</SelectItem>
                      <SelectItem value="跟随">跟随</SelectItem>
                      <SelectItem value="环绕">环绕</SelectItem>
                    </SelectContent>
                  </Select>

                 
                  <Select
                    value={editingScript.finished ? '已完成' : '未完成'}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      finished: value === '已完成'
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="已完成">已完成</SelectItem>
                      <SelectItem value="未完成">未完成</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <Button onClick={handleSaveScript}>{isCreating ? '创建' : '保存'}</Button>
              </div>
            )}
          </DialogContent>
        </Dialog>

        <Dialog open={showGeneratedDialog} onOpenChange={setShowGeneratedDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>生成的脚本</DialogTitle>
            <DialogDescription>请确认以下生成的脚本</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 max-h-[60vh] overflow-y-auto">
            {generatedScripts.map((script, index) => (
              <div key={index} className="p-4 border rounded-lg">
                <div className="flex flex-col gap-2">
                  <div className="flex gap-4">
                    <p className="font-medium">情节:</p>
                    <p>{script.plot}</p>
                  </div>
                  <div className="flex gap-4">
                    <p className="font-medium">地点:</p>
                    <p>{script.location}</p>
                  </div>
                  <div className="flex gap-4">
                    <p className="font-medium">内容:</p>
                    <p>{script.content}</p>
                  </div>
                  <div className="flex gap-4">
                    <p className="font-medium">对白:</p>
                    <p>{script.caption}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setShowGeneratedDialog(false)}>
              取消
            </Button>
            <Button onClick={handleBatchCreate}>
              批量创建
            </Button>
          </div>
        </DialogContent>
      </Dialog>
      </div>
    </div>
  )
}
